import * as PIXI from 'pixi.js';
import { fadeIn } from '../animate/fadeIn';
import { fadeOut } from '../animate/fadeOut';
/**
 * Card
 * Page和Images父类
 * 提供点击切换
 */
export default class Card {
  container = new PIXI.Container()
  nextTime: number[] = []
  constructor(
    private cards: Card[],
    private time: number,
    private ticker: PIXI.Ticker,
  ) {
    this.container.visible = false;
    this.container.interactive = true;
    this.container.on('pointertap', (event: Event) => this.next(event))
  }
  private next(event: Event = null) {
    this.nextTime.forEach(t => clearTimeout(t))
    this.nextTime.length = 0;
    Card.next(this.cards, this, this.ticker)
    if (event) {
      event.stopPropagation();
    }
  }
  // 显示下页
  static next(cards: Card[], card: Card, ticker: PIXI.Ticker) {
    if (!cards.length) return;
    let i = cards.indexOf(card) + 1;
    if (i >= cards.length) {
      i = 0;
    }
    Card.show(cards, i, ticker)
  }
  // 显示首页
  static home(cards: Card[], ticker: PIXI.Ticker) {
    if (!cards.length) return;
    const v = Card.visible(cards)
    if (v === 0) return;
    Card.show(cards, 0, ticker)
  }
  // 显示尾页
  static end(cards: Card[], ticker: PIXI.Ticker) {
    if (!cards.length) return;
    const v = Card.visible(cards)
    const i = cards.length - 1;
    if (v === i) return;
    Card.show(cards, i, ticker)
  }
  // 显示上页
  static up(cards: Card[], ticker: PIXI.Ticker) {
    if (!cards.length) return;
    const i = Card.visible(cards) - 1
    if (i < 0) return;
    Card.show(cards, i, ticker)
  }
  // 显示下页
  static down(cards: Card[], ticker: PIXI.Ticker) {
    if (!cards.length) return;
    const i = Card.visible(cards) + 1
    if (i >= cards.length) return;
    Card.show(cards, i, ticker)
  }
  // 显示指定页
  static async show(cards: Card[], i: number, ticker: PIXI.Ticker) {
    for (const p of cards) {
      if (p.container.visible) {
        await fadeOut(ticker, p.container);
      }
    }
    const c = cards[i];
    if (c.time) {
      c.nextTime.push(setTimeout(() => c.next(), c.time) as unknown as number)
    }
    // 淡入
    await fadeIn(ticker, c.container)
    // 放大
    // await zoom(ticker, c.container)
  }
  // 返回显示页
  static visible(cards: Card[]) {
    for (let i = 0; i < cards.length; i++) {
      if (cards[i].container.visible) {
        return i;
      }
    }
    return -1;
  }
}
